<?php
/**
 * This file is part of Swoft.
 *
 * @link https://swoft.org
 * @document https://doc.swoft.org
 * @contact group@swoft.org
 * @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Middlewares;

use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Swoft\Bean\Annotation\Bean;
use Swoft\Http\Message\Middleware\MiddlewareInterface;
use App\Models\Entity\MUserapi;
use App\Models\Entity\MUserext;


/**
 * Class MerchantSearchMiddleware - Custom middleware
 * @Bean()
 * @package App\Middlewares
 */
class MerchantSearchMiddleware implements MiddlewareInterface
{
    /**
     * @param \Psr\Http\Message\ServerRequestInterface $request
     * @param \Psr\Http\Server\RequestHandlerInterface $handler
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \InvalidArgumentException
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // before request handle

        \Jpay\Helper\wk_monolog(['msg' => '头日志', 'data' => ['get' => $request->getUri()->getQuery(), 'post' => $request->raw(), 'ip' => $request->getHeaderLine('X-Real-IP')]], 'merchant/search');

        $inputData = $request->input();

        if (empty($inputData['userid']) || empty($inputData['vstr'])) {
            throw new \Exception('必要参数为空', 501);
        }

        // if (!is_numeric($inputData['userid']) || strpos($inputData['userid'], '.')) {
        if (!\Jpay\Helper\checkformat($inputData['userid'], 'int')) {
            throw new \Exception('参数不正确', 502);
        }

        // if (!is_numeric($inputData['shoptype']) || strpos($inputData['shoptype'], '.')) {
        if (!\Jpay\Helper\checkformat($inputData['shoptype'], 'int') || !in_array($inputData['shoptype'], \config('JPAY_SHOPTYPE_LIST'))) {
            throw new \Exception('shoptype非法', 502);
        }

        if (!isset($inputData['orderid']) || !preg_match('/^[0-9a-zA-Z]{3,32}$/', $inputData['orderid'])) {
            throw new \Exception('orderid非法', 502);
        }

        $response = $handler->handle($request);

        return $response->withAddedHeader('Merchant-Middleware', 'OK');
    }
}
